package com.zzh.partnersys.controller;

import cn.hutool.core.util.StrUtil;
import com.zzh.partnersys.common.exception.BusinessException;
import com.zzh.partnersys.common.exception.ResultCodeEnum;
import com.zzh.partnersys.common.exception.ResultUtils;
import com.zzh.partnersys.entity.TeamDO;
import com.zzh.partnersys.entity.UserDO;
import com.zzh.partnersys.entity.vo.TeamUserVO;
import com.zzh.partnersys.entity.vo.UserRoomVO;
import com.zzh.partnersys.entity.request.*;
import com.zzh.partnersys.service.TeamService;
import com.zzh.partnersys.service.TeamUIDCacheService;
import com.zzh.partnersys.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.zzh.partnersys.chat.cache.NettyCache.ID_TEAM_MAP;

/**
 * <p>
 * 队伍�?前端控制�?
 * </p>
 *
 * @author zzh
 * @since 2024-07-20
 */
@RestController
@RequestMapping("/team")
public class TeamController {

    @Autowired
    private UserService userService;

    @Autowired
    private TeamService teamService;

    @Autowired
    private TeamUIDCacheService teamUIDCacheService;

    /**
     * 添加队伍
     * @param teamAddRequest 队伍添加请求�?
     * @param request 请求�?
     * @return ResultUtils
     */
    @PostMapping("/add")
    public ResultUtils addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request){
        if (teamAddRequest == null){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }
        //判断是否有权限（有无登录�?
        UserDO currentUserDO = userService.getCurrentUser(request);
        if (currentUserDO == null){
            throw new BusinessException(ResultCodeEnum.NO_AUTH);
        }
        long userId = currentUserDO.getId();
        if (currentUserDO.getId() <= 0){
            throw new BusinessException(ResultCodeEnum.NO_AUTH);
        }
        TeamDO teamDO = new TeamDO();
        teamDO.setUserId(userId);
        String avatarUrl = currentUserDO.getAvatarUrl();
        if (StrUtil.isNotBlank(avatarUrl)){
            teamDO.setImageUrl(avatarUrl);
        }
        BeanUtils.copyProperties(teamAddRequest, teamDO);
        //创建队伍
        Boolean isAdd = teamService.addTeam(teamDO);
        if(!isAdd){
            throw new BusinessException("创建队伍失败",40000);
        }
        //异步缓存
        Set<Long> userIdSet = new HashSet();
        userIdSet.add(userId);
        ID_TEAM_MAP.putIfAbsent(teamDO.getId(), userIdSet);
        return ResultUtils.ok(teamDO.getId());//这里插入成功team会回写的
    }

    /**
     * 查询(带有查询条件)队伍列表(可分�?(带用户信�?
     * @param teamSearchRequest
     * @param request
     * @return
     */
    @PostMapping("/searchTeamAndUserByPage")
    public ResultUtils searchTeamAndUserByPage(@RequestBody TeamSearchRequest teamSearchRequest
                                        ,HttpServletRequest request){
        if (teamSearchRequest == null){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }

        List<TeamUserVO> teamUserVOList =  teamService.searchTeamAndUserByPage(teamSearchRequest,request);
        return ResultUtils.ok(teamUserVOList);
    }

    @PutMapping("/update")
    public ResultUtils updateTeamInfo(@RequestBody TeamUpdateRequest teamUpdateRequest
                                ,HttpServletRequest request){
        if (teamUpdateRequest == null){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }
        boolean isUpdate = teamService.updateTeamInfo(teamUpdateRequest,request);
        if (!isUpdate){
            return ResultUtils.fail("修改失败");
        }else {
            return ResultUtils.ok("修改成功");
        }
    }


    //用户加入队伍
    @PostMapping("/join")
    public ResultUtils userJoinTeam(@RequestBody UserAddTeamRequest userAddTeamRequest
                            ,HttpServletRequest request){
        if (userAddTeamRequest == null){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }
        UserDO currentUserDO = userService.getCurrentUser(request);
        if (currentUserDO == null){
            throw new BusinessException(ResultCodeEnum.NO_AUTH);
        }

        //1.判断参数
        if (null == userAddTeamRequest) {
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }
        Long teamId = userAddTeamRequest.getId();
        if (teamId == null || teamId <= 0) {
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }

        //加入队伍
        boolean isAddTeam = teamService.userJoinTeam(userAddTeamRequest, currentUserDO.getId());
        if (!isAddTeam){
            return ResultUtils.fail("加入队伍失败");
        }else {
            return ResultUtils.ok("加入队伍成功");
        }
    }

    //用户加入队伍
    @GetMapping("/joinInvite")
    public ResultUtils userJoinTeam(Long teamId,HttpServletRequest request){
        if (teamId == null || teamId <= 0){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }
        UserDO currentUserDO = userService.getCurrentUser(request);
        if (currentUserDO == null){
            throw new BusinessException(ResultCodeEnum.NO_AUTH);
        }

        //加入队伍
        boolean isAddTeam = teamService.userJoinTeamInvite(teamId, currentUserDO);
        if (!isAddTeam){
            return ResultUtils.fail("加入队伍失败");
        }else {
            return ResultUtils.ok("加入队伍成功");
        }
    }


    //用户退出队�?
    @DeleteMapping("/quit")
    public ResultUtils quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request){
        if (teamQuitRequest == null){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }
        UserDO currentUserDO = userService.getCurrentUser(request);
        if (currentUserDO == null){
            throw new BusinessException(ResultCodeEnum.NO_AUTH);
        }
        long userId = currentUserDO.getId();
        if (userId <= 0){
            throw new BusinessException(ResultCodeEnum.NO_AUTH);
        }
        //退出队�?
        boolean isQuit = teamService.quitTeam(teamQuitRequest,userId);
        if (isQuit){
            return ResultUtils.ok("退出队伍成功");
        }else{
            return  ResultUtils.fail("退出队伍失败");
        }

    }

    //获取当前用户已加入的队伍
    @GetMapping("/my/join")
    public ResultUtils getMyJoinTeamInfo(HttpServletRequest request){
        if (request == null){
            throw new BusinessException(ResultCodeEnum.NO_AUTH);
        }
        UserDO currentUserDO = userService.getCurrentUser(request);
        if (currentUserDO == null){
            throw new BusinessException(ResultCodeEnum.NO_AUTH);
        }
        long userId = currentUserDO.getId();
        if (userId <= 0){
            throw new BusinessException(ResultCodeEnum.NO_AUTH);
        }
        List<TeamUserVO> teamUserVOList =  teamService.getMyJoinTeamInfo(userId);
        return ResultUtils.ok(teamUserVOList);
    }


    //获取当前用户创建的队�?
    @GetMapping("/my/create")
    public ResultUtils getMyCreateTeamInfo(HttpServletRequest request){
        if (request == null){
            throw new BusinessException(ResultCodeEnum.NO_AUTH);
        }
        UserDO currentUserDO = userService.getCurrentUser(request);
        if (currentUserDO == null){
            throw new BusinessException(ResultCodeEnum.NO_AUTH);
        }
        long userId = currentUserDO.getId();
        if (userId <= 0){
            throw new BusinessException(ResultCodeEnum.NO_AUTH);
        }
        // todo 还可以优化，因为我们缓存的队伍和用户的信�?可以直接拿到id去查询信�?
        List<TeamUserVO> teamUserVOList =  teamService.getMyCreateTeamInfo(userId);
        return ResultUtils.ok(teamUserVOList);
    }

    //解散队伍
    @DeleteMapping("/dissolution")
    public ResultUtils dissolutionTeam(@RequestParam("teamId") long teamId,HttpServletRequest request){
        UserDO currentUserDO = userService.getCurrentUser(request);
        if (currentUserDO == null){
            throw new BusinessException(ResultCodeEnum.NO_AUTH);
        }
        long userId = currentUserDO.getId();
        if (userId <= 0){
            throw new BusinessException(ResultCodeEnum.NO_AUTH);
        }
        if (teamId <= 0){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }
        //解散
        boolean isDissolution = teamService.dissolutionTeam(userId,teamId);
        //清除缓存
        if (isDissolution){
            teamUIDCacheService.CacheMapTeamUIDClear(teamId);
            return ResultUtils.ok(null);
        }else {
            return ResultUtils.fail(null);
        }
    }


    //查询某个队伍的详细信�?
    @PostMapping("/selectOneTeam")
    public ResultUtils selectOneTeam(@RequestBody TeamSelectOneRequest teamSelectOneRequest){
        if (teamSelectOneRequest == null){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }
        //查询
        TeamUserVO teamUserVO = teamService.selectOneTeam(teamSelectOneRequest);
        return ResultUtils.ok(teamUserVO);
    }

    //查询聊天�?队伍聊天�?好友聊天�?=>map中存放的�?
    @GetMapping("/selectChatRoom")
    public ResultUtils selectChatRoomByUserId(@RequestParam("userId") Long userId,HttpServletRequest request){
        if (userId == null || userId <= 0){
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }
        UserDO currentUserDO = userService.getCurrentUser(request);

        //查询 UserRoomVO 队伍标识、单聊群聊标记type�?队伍备注、队伍名、用户id、好友id、队伍用户id、头像、消息的最新时间、最新的消息内容�?
        List<UserRoomVO> userRoomVOList = teamService.selectChatRoomByUserId(userId, currentUserDO);
        return ResultUtils.ok(userRoomVOList);
    }



    //邀请好友加入队�?
    @PostMapping("/invite")
    public ResultUtils inviteFriend(@RequestBody InviteAddTeamRequest inviteAddTeamRequest,HttpServletRequest request) {
        //参数校验
        if (inviteAddTeamRequest == null) {
            throw new BusinessException(ResultCodeEnum.PARAMS_ERROR);
        }
        if (request == null){
            throw new BusinessException(ResultCodeEnum.NO_AUTH);
        }
        Long[] friendIds = inviteAddTeamRequest.getFriendIds();
        Long teamId = inviteAddTeamRequest.getTeamId();
        if (friendIds == null || friendIds.length == 0){
            throw new BusinessException("请选择好友邀请加入队伍",4006);
        }
        if (teamId == null || teamId <= 0){
            throw new BusinessException("请选择队伍",4006);
        }
        teamService.invite(friendIds,teamId,request);
        return ResultUtils.ok(null);
    }



}

